package com.hz.api.admin.web.config.aop;

import com.alibaba.fastjson.JSON;
import com.hz.api.admin.model.bo.UserInfoBO;
import com.hz.api.admin.model.dao.ApiOperatrLogDao;
import com.hz.api.admin.model.entity.ApiOperateLogEntity;
import com.hz.api.admin.web.config.aop.annotation.OperateLogAnnotation;
import com.hz.api.admin.web.config.thread.UserContextHolder;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * @author zhaolei01
 * Date 2024/8/21
 */
@Aspect
@Component
@Slf4j
public class AuditLogInterceptor {
    @Pointcut("@annotation(com.hz.api.admin.web.config.aop.annotation.OperateLogAnnotation)")
    public void annotationPointcut() {
    }

    @Autowired
    private ApiOperatrLogDao apiOperatrLogDao;
    @AfterReturning("annotationPointcut()")
    public void afterReturning(JoinPoint joinPoint) {
        try {
            MethodSignature signature = (MethodSignature) joinPoint.getSignature();
            if (signature != null) {
                OperateLogAnnotation auditLogAnnotation = signature.getMethod().getAnnotation(OperateLogAnnotation.class);
                UserInfoBO accountInfoDTO = UserContextHolder.getAccountInfoDTO();
                if (accountInfoDTO == null){
                    return;
                }
                ApiOperateLogEntity auditLogRequest = ApiOperateLogEntity
                        .builder()
                        .appCode(auditLogAnnotation.appCode())
                        .sourceNo("0")
                        .userType(accountInfoDTO.getType())
                        .userId(accountInfoDTO.getUsername())
                        .modularName(auditLogAnnotation.modularName())
                        .modularType(auditLogAnnotation.modularType())
                        .scene(auditLogAnnotation.scene())
                        .requestData(getParam(signature.getParameterNames(), joinPoint.getArgs()))
                        .build();
                apiOperatrLogDao.insert(auditLogRequest);
            }
        } catch (Exception e) {
            log.error("afterReturning异常", e);
        }

    }

    private String getParam(String[] argNames, Object[] args) {
        Map<String, Object> map = new HashMap<>(argNames.length);
        for (int i = 0; i < argNames.length; i++) {
            map.put(argNames[i], args[i]);
        }
        return JSON.toJSONString(map);
    }

}
